﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace UCL.Web.CustomControls
{
    /// <summary>
    /// 文件控件
    /// </summary>
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:FileField runat=server></{0}:FileField>")]
    public class FileField : CompositeControl
    {
        private FileUpload fuField;
        private HiddenField hidMode, hidValue;

        /// <summary>
        /// 上传路径
        /// <para>如：/upload/face/</para>
        /// </summary>
        public string UploadPath { get; set; }

        /// <summary>
        /// 设置控件的值
        /// </summary>
        public string Value { get; set; }

        /// <summary>
        /// 设置控件二进制值
        /// </summary>
        public byte[] ValueData { get; set; }

        /// <summary>
        /// 预绘制事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            Page.PreRenderComplete += PagePreRenderComplete;
            base.OnPreRender(e);
        }

        /// <summary>
        /// 页面绘制完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PagePreRenderComplete(object sender, EventArgs e)
        {
            this.Page.ClientScript.RegisterStartupScript(typeof(FileField), "FileField", "function FileFieldToggle(o){var $o=$(o);$o.prev().toggle();$o.prev().prev().toggle();$o.text(($o.text()=='[更换]'?'[取消]':'[更换]'));$o.next().val($o.text())};", true);
        }

        /// <summary>
        /// 创建子对象
        /// </summary>
        protected override void CreateChildControls()
        {
            this.hidMode = new HiddenField();
            this.hidValue = new HiddenField();
            this.fuField = new FileUpload();
            if (string.IsNullOrEmpty(this.Value) && (this.ValueData == null))
            {
                this.hidMode.Value = "[取消]";
            }
            else
            {
                this.hidMode.Value = "[更换]";
                this.hidValue.Value = this.Value;
                this.fuField.Attributes["style"] = "display:none;";
            }
            this.Controls.Add(this.hidMode);
            this.Controls.Add(this.hidValue);
            this.Controls.Add(this.fuField);
        }

        /// <summary>
        /// 重绘控件界面
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            if (this.ValueData != null)
            {
                Random rnd = new Random();
                string sTmpPath = string.Format("{0}/tmp{1}{2}.jpg", this.UploadPath, DateTime.Now.ToString("yyMMddHHmmss"), rnd.Next(999));
                File.WriteAllBytes(System.Web.HttpContext.Current.Server.MapPath(sTmpPath), this.ValueData);
                this.Value = sTmpPath;
            }
            if (string.IsNullOrEmpty(this.Value))
            {
                this.fuField.RenderControl(writer);
                this.hidMode.RenderControl(writer);
                return;
            }
            if (this.Value.IsValidImageFile())
            {
                writer.Write("<a href=\"{0}\" target=\"_blank\"><img src=\"{0}\" alt=\"\" style=\"width:60px;height:60px;\" /></a>".Fmt(this.Value));
            }
            else
            {
                writer.Write("<a href=\"{0}\" target=\"_blank\">{0}</a>".Fmt(this.Value));
            }

            this.fuField.RenderControl(writer);
            writer.Write("<a href=\"###\" onclick=\"FileFieldToggle(this);\">[更换]</a>");
            this.hidMode.RenderControl(writer);
            this.hidValue.RenderControl(writer);
        }
        /// <summary>
        /// 获取值
        /// </summary>
        /// <returns></returns>
        public string GetValue()
        {
            if (this.hidMode.Value == "[取消]") return this.fuField.UploadFile(this.UploadPath, "file");
            return this.hidValue.Value;
        }
        /// <summary>
        /// 获取值数据
        /// </summary>
        /// <returns></returns>
        public byte[] GetValueData()
        {
            if (this.hidMode.Value == "[取消]") return this.fuField.UploadFileData("file");
            return File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath(this.hidValue.Value));
        }
    }
}
